<template>
  <view class="message-page">
    <nav-bar title="消息" :back="false" @load="handleLoadNav" textAlign="center"></nav-bar>
    <scroll-view scroll-y="true" class="message-list-container" :style="{height:viewHeight+'px'}" refresher-enabled
      :refresher-triggered="refresher" @refresherrefresh="handleRefresher">
      <block v-for="item in messageData" :key="item.type">
        <message-block :data="item"></message-block>
      </block>
    </scroll-view>
  </view>
</template>

<script>
  import {
    getChatMsgApi,
    getMsgConfigApi
  } from "@/api/message/message.js";
  export default {
    data() {
      return {
        messageData: [],
        viewHeight: 0, //可移动视图的高度
        refresher: false
      };
    },
    onShow() {
      this.handleRefresherTOInit();
    },
    methods: {
      handleLoadNav({
        height,
        navHeight
      }) {
        // 可移动视图的高度 = 视图高度 - 导航栏高度
        this.viewHeight = height - navHeight;
      },
      async handleRefresher() {
        await this.handleGetMsgConfigApi();
        this.getChatMsgApi();
      },
      async handleRefresherTOInit() {
        await this.handleGetMsgConfigApi();
        this.getChatMsgApi(false);
      },
      // 获取消息配置
      async handleGetMsgConfigApi() {
        let {
          data: res
        } = await getMsgConfigApi();
        if (res.success) {
          let list = res.data.list;
          let obj = {};
          for (let i in list) {
            obj[list[i].type] = list[i];
          }
          getApp().globalData.message_config = obj;
        }
        return res
      },
      // 获取消息列表
      async getChatMsgApi(bool = true) {
        if (bool) {
          if (this.refresher) {
            return;
          }
          this.refresher = true;
        }

        const {
          data: result
        } = await getChatMsgApi();
        if (result.success) {
          let list = result.data.list;
          this.messageData = list.filter((item) => {
            return item.type != 3
          });
          let msgNum = this.messageData.reduce((num, item) => {
            return num + item.unreadNum;
          }, 0);
          if (msgNum > 0) {
            uni.setTabBarBadge({
              index: 2,
              text: msgNum > 99 ? "99+" : String(msgNum),
            });
          } else {
            uni.removeTabBarBadge({
              index: 2,
            });
          }
        }
        setTimeout(() => {
          this.refresher = false;
        }, 300)
      },
    },
  };
</script>

<style lang="scss" scoped>
  .message-page {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: #eef2f4;

    .message-list-container {}
  }
</style>